package com.jt.controller;

import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.vo.PageResult;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public List<User> findAll(){

        return userService.findAll();
    }

    @PostMapping("/login")
    public SysResult login(@RequestBody User user){
        String token = userService.login(user);
        if (token == null){
            return SysResult.fail();
        }
        return SysResult.success(token);
    }

    @GetMapping("/list")
    public SysResult getUserList(PageResult pageResult){
        pageResult = userService.getUserList(pageResult);
        return SysResult.success(pageResult);
    }

    @Transactional
    @PutMapping("/status/{id}/{status}")
    public SysResult status(User user){
        userService.updateStatus(user);
        return SysResult.success();
    }

    @Transactional
    @PostMapping("/addUser")
    public SysResult addUser(@RequestBody User user){
        userService.addUser(user);
        return SysResult.success();
    }

    @GetMapping("/{id}")
    public SysResult findUserById(@PathVariable int id){
        return SysResult.success(userService.findUserById(id));
    }

    @Transactional
    @PutMapping("/updateUser")
    public SysResult updateUser(@RequestBody User user){
        Integer rows = userService.updateUser(user);
        if (rows == 0) return SysResult.fail();
        return SysResult.success();
    }

    @Transactional
    @DeleteMapping("/{id}")
    public SysResult deleteUserById(User user){
        userService.deleteUserById(user);
        return SysResult.success();
    }
}
